package com.kldy8.kldyw;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.kldy8.kldyw.sharedpreference.SharedPreUtil;
import com.kldy8.kldyw.sharedpreference.UserEntity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.system.UpdataManager;
import com.kldy8.kldyw.system.UpdataManagerInf;

import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import okhttp3.Request;

public class WelComeActivity extends AppCompatActivity implements UpdataManagerInf
{
    private int TIME = 1000;
    private final  int WRITE_CODE = 123;

    TimerTask task = new TimerTask()
    {
        public void run()
        {
            Intent i = new Intent();
            i.setClass(WelComeActivity.this, Main2Activity.class);
            startActivity(i);
            overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            finish();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wel_come);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED)
        {
                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.KILL_BACKGROUND_PROCESSES,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE,Manifest.permission.GET_ACCOUNTS
                        ,Manifest.permission.CAMERA   ,Manifest.permission.RECORD_AUDIO
                        ,Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS},
                        WRITE_CODE);
        }
        else
        {
            checke();
        }
    }

    private void checke()
    {
        UpdataManager manager = new UpdataManager(WelComeActivity.this,this);
        manager.isUpdate();
    }


    private void doIt()
    {
        SharedPreUtil.initSharedPreference(this);
        UserEntity entity = SharedPreUtil.getInstance().getUser();

        if (entity == null)
        {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Timer timer = new Timer();
                    timer.schedule(task, TIME);
                }
            }).start();

            return;
        }
        else
        {
            final String phone = entity.getUserName();
            final String password = entity.getPassword();

            if (phone == null || password == null)
            {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Timer timer = new Timer();
                        timer.schedule(task, TIME);
                    }
                }).start();
                return;
            }

            TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
            String client_key = tm.getDeviceId();

            ServerApi.login(phone, password, client_key, new ServerCallBack() {
                @Override
                public void onError(Request request, Exception e) {
                    Log.e("onError", e.getMessage());
                    Intent i = new Intent();
                    i.setClass(WelComeActivity.this, Main2Activity.class);
                    startActivity(i);
                    overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                    finish();
                }

                @Override
                public void onResponse(String response) throws JSONException {
                    Log.e("......", response.toString());
                    JSONObject jsonObject = new JSONObject(response);
                    if ("0".equals(jsonObject.optString("code"))) {
                        UserEntity entity = SharedPreUtil.getInstance().getUser();
                        entity.setUserName(phone);
                        entity.setPassword(password);
                        SharedPreUtil.getInstance().putUser(entity);

                        JSONObject objectData = jsonObject.optJSONObject("data");
                        String username = objectData.optString("username");
                        String token = objectData.optString("token");
                        String member_id = objectData.optString("member_id");
                        String f_person = objectData.optString("f_person");
                        String auth_personal = objectData.optString("auth_personal");
                        String auth_enterprise = objectData.optString("auth_enterprise");
                        String auth_actor = objectData.optString("auth_actor");
                        String auth_writer = objectData.optString("auth_writer");

                        ((SystemSet) getApplication()).setToken(token);
                        ((SystemSet) getApplication()).setMember_id(member_id);
                        ((SystemSet) getApplication()).setF_person(f_person);
                        ((SystemSet) getApplication()).setAuth_personal(auth_personal);
                        ((SystemSet) getApplication()).setAuth_enterprise(auth_enterprise);
                        ((SystemSet) getApplication()).setAuth_actor(auth_actor);
                        ((SystemSet) getApplication()).setAuth_writer(auth_writer);
                    }
                    else  if ("10003".equals(jsonObject.optString("code")))
                    {
                    }
                    else  if ("10008".equals(jsonObject.optString("code")))
                    {
                    }
                    else  if ("10002".equals(jsonObject.optString("code")))
                    {
                    }
                    else
                    {

                    }

                    Intent i = new Intent();
                    i.setClass(WelComeActivity.this, Main2Activity.class);
                    startActivity(i);
                    finish();
                }
            });
        }

    }


    public int getVersion() {
        int version = 0;
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            version = info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }


    protected File downLoadFile(String httpUrl) {
        // TODO Auto-generated method stub
        final String fileName = "updata.apk";
        File tmpFile = new File("/sdcard/update");
        if (!tmpFile.exists()) {
            tmpFile.mkdir();
        }
        final File file = new File("/sdcard/update/" + fileName);

        try {
            URL url = new URL(httpUrl);
            try {
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                InputStream is = conn.getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[256];
                conn.connect();
                double count = 0;
                if (conn.getResponseCode() >= 400) {
                    Toast.makeText(WelComeActivity.this, "连接超时", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    while (count <= 100) {
                        if (is != null) {
                            int numRead = is.read(buf);
                            if (numRead <= 0) {
                                break;
                            } else {
                                fos.write(buf, 0, numRead);
                            }

                        } else {
                            break;
                        }

                    }
                }

                conn.disconnect();
                fos.close();
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }

        return file;
    }
//打开APK程序代码

    private void openFile(File file)
    {
        // TODO Auto-generated method stub
        Log.e("OpenFile", file.getName());
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);
        finish();
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case WRITE_CODE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    // Permission 允许
                    checke();
                }
                else
                {
                    // Permission 拒绝
                    Toast.makeText(WelComeActivity.this, "读取联系人被拒绝", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void needUpdata()
    {
//        doIt();
    }

    @Override
    public void notneedUpdata()
    {
        doIt();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("requestCode:",requestCode+"");
        Log.e("resultCode:",resultCode+"");
    }
}
